package com.health.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.health.dao.SetmealDao;
import com.health.service.SetmealService;
import com.healthcommon.entity.PageResult;
import com.healthcommon.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 选择dubbo注解来暴露服务
 * */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImp implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0){
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
    }

    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    public void delete(Integer id) {
//        先删除关联表的记录
        setmealDao.deleteAssociation(id);
//        然后再删除套餐表的记录
        setmealDao.delectSetmealById(id);

    }

    public Setmeal findById(Integer id) {
        Setmeal setmeal=setmealDao.selectfindById(id);
        return setmeal;
    }

    public Integer[] findCheckItemIdsByCheckGroupId(Integer id) {
        return setmealDao.findCheckItemIdsBySetmealId(id);
    }

    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.updateSetmeal(setmeal);
        setmealDao.delectSetmealAndCheckgroupById(setmeal.getId());
        if (checkgroupIds != null && checkgroupIds.length > 0){
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
    }

    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    public Setmeal findByIdAll(int id) {
        return setmealDao.selectfindByIdAll(id);
    }

    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //绑定套餐和检查组的多对多关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<String,Integer>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }


}
